package com.weme.matching.view

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapShader
import android.graphics.Canvas
import android.graphics.Matrix
import android.graphics.Paint
import android.graphics.Shader
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatImageView

class CenteredCircleImageView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : AppCompatImageView(context, attrs, defStyleAttr) {
    private var mShaderBitmap: Bitmap? = null
    private val mCommonPaint = Paint(Paint.ANTI_ALIAS_FLAG)
    private val matrix = Matrix()

    fun setShaderBitmap(bitmap: Bitmap) {
        mShaderBitmap = bitmap
        invalidate() // 重新绘制视图
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        mShaderBitmap?.let { bitmap ->
            val save = canvas.save()

            // 将图片平移到中心位置
            matrix.setTranslate(
                (width - bitmap.width) / 2f,
                (height - bitmap.height) / 2f
            )

            // 创建 BitmapShader 并设置平移后的矩阵
            val bitmapShader = BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP)
            bitmapShader.setLocalMatrix(matrix)

            // 将 BitmapShader 设置给 Paint
            mCommonPaint.shader = bitmapShader

            // 绘制圆形图像
            val radius = Math.min(width, height) / 2f
            canvas.drawCircle(width / 2f, height / 2f, radius - 2, mCommonPaint)

            mCommonPaint.shader = null // 清除 Shader
            canvas.restoreToCount(save) // 恢复保存的状态
        }
    }
}
